<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录类型" prop="recordType">
        <el-select v-model="queryParams.recordType" placeholder="请选择记录类型" clearable>
          <el-option
            v-for="item in recordTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--           :disabled="single"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['wjq:answerrecord:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['wjq:answerrecord:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wjq:answerrecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wjq:answerrecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="answerrecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <!-- 新增：用户昵称列 -->
      <el-table-column label="用户昵称" align="center" prop="sysYouYouUser.nickName" />
      <el-table-column label="总题数" align="center" prop="totalCount" />
      <!-- 答对题目列表（带弹窗） -->
            <el-table-column label="答对题目ID列表" align="center">
              <template slot-scope="scope">
                <span
                  class="id-list"
                  @click="showQuestionDetail(scope.row.correctList, 'correct',scope.row.id)"
                >
                  {{ scope.row.correctList }}
                </span>
              </template>
            </el-table-column>

            <!-- 答错题目列表（带弹窗） -->
            <el-table-column label="答错题目ID列表" align="center">
              <template slot-scope="scope">
                <span
                  class="id-list"
                  @click="showQuestionDetail(scope.row.wrongList, 'wrong',scope.row.id)"
                >
                  {{ scope.row.wrongList }}
                </span>
              </template>
            </el-table-column>

            <!-- 未答题目列表（带弹窗） -->
            <el-table-column label="未答题目ID列表" align="center">
              <template slot-scope="scope">
                <span
                  class="id-list"
                  @click="showQuestionDetail(scope.row.unansweredList, 'unanswered',scope.row.id)"
                >
                  {{ scope.row.unansweredList }}
                </span>
              </template>
            </el-table-column>

      <el-table-column label="记录类型" align="center" prop="recordType">
        <template slot-scope="scope">
          <span>{{ scope.row.recordType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="耗时" align="center" prop="timeUsedStr" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wjq:answerrecord:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wjq:answerrecord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 题目详情弹窗 -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          width="60%"
          :close-on-click-modal="false"
        >
          <div v-loading="detailLoading" class="question-detail-container">
            <div v-if="questionDetails.length === 0" class="empty-text">
              暂无题目详情
            </div>
            <div v-else class="question-list">
              <div
                class="question-item"
                v-for="(question, index) in questionDetails"
                :key="question.id"
              >
                <div class="question-header">
                  <span class="question-index">{{ index + 1 }}. 题目 ID: {{ question.id }}</span>
                  <span
                    class="question-type"
                    :class="{
                      'correct-type': currentType === 'correct',
                      'wrong-type': currentType === 'wrong',
                      'unanswered-type': currentType === 'unanswered'
                    }"
                  >
                    {{ typeTextMap[currentType] }}
                  </span>
                </div>
                <div class="question-content">
                   <!-- 显示标题 -->
                    <h4 class="question-title">
                      {{ index + 1 }}. {{ question.title }}
                    </h4>

                </div>
              </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
          </div>
        </el-dialog>

    <!-- 添加或修改答题记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="总题数" prop="totalCount">
          <el-input v-model="form.totalCount" placeholder="请输入总题数" />
        </el-form-item>
        <el-form-item label="答对题目ID列表" prop="correctList">
          <el-input v-model="form.correctList" placeholder="请输入答对题目ID列表" />
        </el-form-item>
        <el-form-item label="答错题目ID列表" prop="wrongList">
          <el-input v-model="form.wrongList" placeholder="请输入答错题目ID列表" />
        </el-form-item>
        <el-form-item label="未答题目ID列表" prop="unansweredList">
          <el-input v-model="form.unansweredList" placeholder="请输入未答题目ID列表" />
        </el-form-item>
        <el-form-item label="记录类型" prop="recordType">
          <el-select v-model="form.recordType" placeholder="请选择记录类型">
            <el-option
              v-for="item in recordTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="耗时" prop="timeUsed">
          <el-input v-model="form.timeUsed" placeholder="请输入耗时" />
        </el-form-item>
       <!-- <el-form-item label="0是已删除，1是保留" prop="del">
          <el-input v-model="form.del" placeholder="请输入0是已删除，1是保留" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAnswerrecord, getAnswerrecord, delAnswerrecord, addAnswerrecord, updateAnswerrecord,getBatchQuestions } from "@/api/wjq/answerrecord"
export default {
  name: "Answerrecord",
  // 移除数据字典依赖
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 答题记录表格数据
      answerrecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        sysYouYouUser: {
                nickName: ""
            },
        recordType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        totalCount: [
          { required: true, message: "总题数不能为空", trigger: "blur" }
        ],
        recordType: [
          { required: true, message: "记录类型不能为空", trigger: "change" }
        ],
        del: [
          { required: true, message: "0是已删除，1是保留不能为空", trigger: "blur" }
        ]
      },

      // 自定义记录类型选项
      recordTypeOptions: [
        { value: '章节训练', label: '章节训练' },
        { value: '模拟考试', label: '模拟考试' },
        { value: '院校真题', label: '院校真题' }
      ],

      // 弹窗相关数据
      dialogVisible: false,
      dialogTitle: '',
      detailLoading: false,
      questionDetails: [],
      currentType: '' // 记录当前是哪种类型的题目列表（correct/wrong/unanswered）
    }
  },
  computed: {
    // 类型文本映射
    typeTextMap() {
      return {
        correct: '正确',
        wrong: '错误',
        unanswered: '未答'
      };
    }
  },
  created() {
    this.getList()
  },

  methods: {
    /** 查询答题记录列表 */
    getList() {
      this.loading = true
      listAnswerrecord(this.queryParams).then(response => {
        this.answerrecordList = response.rows
        this.total = response.total
        this.loading = false
        console.log(this.answerrecordList)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        nickName: null,
        totalCount: null,
        correctList: null,
        wrongList: null,
        unansweredList: null,
        recordType: null,
        timeUsedStr: null,
        createTime: null,
        del: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加答题记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAnswerrecord(id).then(response => {
        this.form = response.data
        this.form.nickName = this.form.sysYouYouUser?.nickName || ''
        this.open = true
        this.title = "查看答题记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAnswerrecord(this.form).then(() => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAnswerrecord(this.form).then(() => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除答题记录编号为"' + ids + '"的数据项？').then(function() {
        return delAnswerrecord(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wjq/answerrecord/export', {
        ...this.queryParams
      }, `answerrecord_${new Date().getTime()}.xlsx`)
    },

    // 新增：显示题目详情
    showQuestionDetail(idList, type, recordId) {
      // 处理ID列表（假设ID列表是逗号分隔的字符串，如"1,2,3"）
      const ids = idList ? idList.split(',').map(id => id.trim()) : [];
      console.log(ids)
      if (ids.length === 0) {
        this.$message.warning('没有题目ID');
        return;
      }

      // 设置弹窗标题和类型
      this.currentType = type;
      this.dialogTitle = `${this.typeTextMap[type]}题目详情`;
      this.dialogVisible = true;
      this.detailLoading = true;

      // 调用接口获取题目详情
      this.getQuestionDetails(ids);
    },

    // 新增：获取题目详情
    getQuestionDetails(ids) {
      // 处理ID列表（假设ids是题目ID数组）
      if (ids.length === 0) {
        this.$message.warning('没有题目ID');
        return;
      }

      console.log("yughj")
      this.detailLoading = true;
      getBatchQuestions(ids).then(response => {
        this.questionDetails = response.data || [];

        // 调试用：查看获取到的题目数据
        console.log('获取到的题目列表:', this.questionDetails);

        this.detailLoading = false;
      }).catch(error => {
        console.error('获取题目详情失败', error);
        this.detailLoading = false;
        this.$message.error('获取题目详情失败');
      });
    }
  }
}
</script>



<style scoped>
/* 点击样式 */
.id-list {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
}

/* 弹窗样式 */
.question-detail-container {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 10px;
}

.question-list {
  margin-top: 10px;
}

.question-item {
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  margin-bottom: 15px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px dashed #e6e6e6;
}

.question-index {
  font-weight: bold;
}

.question-type {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: #fff;
}

.correct-type {
  background-color: #67c23a;
}

.wrong-type {
  background-color: #f56c6c;
}

.unanswered-type {
  background-color: #909399;
}

.question-content {
  line-height: 1.6;
}

.question-options {
  margin: 10px 0;
  padding-left: 20px;
}

.question-options li {
  margin: 5px 0;
}

.question-answer {
  margin: 10px 0;
  color: #67c23a;
}

.question-analysis {
  margin: 10px 0;
  color: #409EFF;
  font-style: italic;
}

.empty-text {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}
</style>
